<template>
  <div class="comments">
    <div
      v-for="(item, i) in comments"
      :key="i"
      class="author-title reply-father"
    >
      <el-avatar class="header-img" :size="40" :src="item.avatar"></el-avatar>
      <!-- 作者信息——姓名，时间 -->
      <div class="author-info">
        <span class="author-name">{{ item.userName }}</span>
        <span class="author-time">{{ item.time }}</span>
      </div>
      <!-- 子评论数 -->
      <div class="icon-btn">
        <span
          class="delete-btn"
          v-if="isShowDelete(item.userId)"
          @click="deleteComment(item)"
        >
          删除</span
        >
        <span class="reply-comment-btn" @click="showCommentInput(i, 1)">
          <span class="iconfont icon-reply">&#xe606;</span>
          <span>回复</span>
        </span>
        <span
          @click="showReplyList(i, item.commentId)"
          ref="outerComment"
          class="comment-btn"
        >
          <i class="iconfont">&#xe624;</i>
        </span>
      </div>
      <!-- 作者评论的内容 -->
      <div class="talk-box">
        <p>
          <span class="reply">{{ item.comment }}</span>
        </p>
      </div>
      <!-- 回复作者的输入框 -->
      <div class="input-comment input-in-comment" v-if="isShowInput[i]">
        <el-row :gutter="20">
          <el-col :span="2">
            <div class="grid-content content-left">
              <img :src="$store.state.user.avatar" class="img-face" />
            </div>
          </el-col>
          <el-col :span="19">
            <div class="grid-content">
              <div class="comment-content">
                <el-form ref="commentForm" :model="commentForm">
                  <el-form-item>
                    <el-input
                      ref="commentInInput"
                      type="textarea"
                      v-model="commentForm.content"
                      :placeholder="`回复 ${item.userName}`"
                      maxlength="100"
                      show-word-limit
                      @blur="hiddenCommentInput(i, 1)"
                    >
                    </el-input>
                  </el-form-item>
                </el-form>
              </div>
            </div>
          </el-col>
          <el-col :span="1">
            <div class="grid-content">
              <el-button
                type="primary"
                class="submit-comment green-button"
                @mousedown.native="
                  sendComment(item.commentId, i, item.commentId)
                "
              >
                发布
              </el-button>
            </div>
          </el-col>
        </el-row>
      </div>
      <!-- 回复评论的评论 -->
      <div class="comments" style="padding-left: 50px" v-if="isShowComments[i]">
        <div
          v-for="(comment, j) in commentsReply"
          :key="j"
          class="author-title reply-father"
        >
          <el-avatar
            class="header-img"
            :size="40"
            :src="comment.avatar"
          ></el-avatar>
          <!-- 作者信息——姓名，时间 -->
          <div class="author-info">
            <span class="author-name">{{ comment.userName }}</span>
            <span class="author-time">{{ comment.time }}</span>
          </div>
          <!-- 子评论数 -->
          <div class="icon-btn">
            <span
              class="delete-btn"
              v-if="isShowDelete(comment.userId)"
              @click="deleteCommentReply(comment, j)"
              >删除</span
            >
            <span class="reply-comment-btn" @click="showCommentInput(j, 2)">
              <span class="iconfont icon-reply">&#xe606;</span>
              <span>回复</span>
            </span>
          </div>
          <!-- 作者评论的内容 -->

          <div class="talk-box">
            <p>
              <!-- <span v-show="comment.to !== ''" class="reply-to">回复{{ replyTo(comment.responseid) }}:</span> -->
              <span v-show="comment.to !== ''" class="reply-to"
                >回复{{ comment.resName }}:</span
              >
              <span class="reply">{{ comment.comment }}</span>
            </p>
          </div>
          <!-- 回复作者的输入框 -->
          <div
            class="input-comment input-in-comment"
            v-if="comment.isShowInput"
          >
            <el-row :gutter="20">
              <el-col :span="2">
                <div class="grid-content content-left">
                  <img :src="$store.state.user.avatar" class="img-face" />
                </div>
              </el-col>
              <el-col :span="19">
                <div class="grid-content">
                  <div class="comment-content">
                    <el-form ref="commentForm" :model="commentForm">
                      <el-form-item>
                        <el-input
                          ref="commentInInput"
                          type="textarea"
                          v-model="commentForm.content"
                          :placeholder="`回复 ${comment.userName}`"
                          maxlength="100"
                          show-word-limit
                          @blur="hiddenCommentInput(j, 2)"
                        >
                        </el-input>
                      </el-form-item>
                    </el-form>
                  </div>
                </div>
              </el-col>
              <el-col :span="1">
                <div class="grid-content">
                  <el-button
                    type="primary green-button"
                    class="submit-comment"
                    @mousedown.native="
                      sendComment(comment.commentId, i, item.commentId)
                    "
                  >
                    发布
                  </el-button>
                </div>
              </el-col>
            </el-row>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { Message } from "element-ui";
import { renderTime } from "@/utils/tools.js";
export default {
  props: ["comments", "user"],
  data() {
    return {
      commentsReply: [], //子评论数组
      isShowComments: [], //是否展示子评论
      isShowInput: [], //是否展示回复输入框（楼主的）
      //回复
      commentForm: {
        content: "",
      },
      commentReplyForm: {
        content: "",
      },
    };
  },
  computed: {
    replyTo() {
      return function (commentId) {
        for (let item of this.comments) {
          // console.log('我是本条id的回复评论id'+commentId);
          // console.log('我是评论id'+item.commentId);
          if (item.commentId === commentId) {
            return item.userName;
          }
        }
        // if (this.commentsReply) {
        //   for (let item of this.commentsReply) {
        //     if (item.commentId == commentId) return item.userName;
        //   }
        // }
        // return "";
      };
    },
    isShowDelete() {
      return function (userId) {
        if (this.$store.state.user.userId) {
          if (userId === this.$store.state.user.userId) return true;
          else return false;
        } else {
          return false;
        }
      };
    },
  },
  watch: {
    //对数组开启深度监听
    isShowComments: {
      handler() {
        // console.log('isShowComments:'+this.isShowComments);
      },
      deep: true,
    },

    isShowInput: {
      handler() {},
      deep: true,
    },
    commentsReply: {
      handler() {},
      deep: true,
    },
  },
  methods: {
    //失去焦点，收起评论回复
    hiddenCommentInput(i, num) {
      // this.$refs['commentForm'].resetFields();
      if (num == 1)
        //回复楼主
        this.isShowInput.splice(i, 1, false);
      else {
        //回复楼主下面的评论
        let temp = this.commentsReply[i];
        temp.isShowInput = !this.commentsReply[i].isShowInput;
        this.commentsReply.splice(i, 1, temp);
      }
    },
    //展开评论回复输入框
    showCommentInput(i, num) {
      if (this.$store.state.user.isLogin) {
        if (num == 1) {
          this.isShowInput.splice(i, 1, !this.isShowInput[i]);
          this.$nextTick(() => {
            if (this.$refs.commentInInput[0]) {
              this.$refs.commentInInput[0].focus();
            }
          });
        } else {
          let temp = this.commentsReply[i];
          temp.isShowInput = !this.commentsReply[i].isShowInput;
          this.commentsReply.splice(i, 1, temp);
          this.$nextTick(() => {
            if (this.$refs.commentInInput[0]) {
              this.$refs.commentInInput[0].focus();
            }
          });
        }
      } else {
        Message({
          message: "未登录或者登录状态已过期，清重新登录",
          type: "error",
          duration: 1000,
        });
      }
    },
    //显示/隐藏子评论
    async showReplyList(i, commentId) {
      if (this.isShowComments[i] === false) {
        //根据评论id发送请求获取子评论
        let res = await this.$api.getComments(commentId);
        if (res.code === 200) {
          for (let item of res.rows) {
            item.time = renderTime(item.time);
            item.avatar = this.$api.BASEURL + item.avatar;
          }
          this.commentsReply = res.rows;
        }
        // console.log("我是子评论");
        // console.log(res);
      }
      //改变数据是监听不到的
      this.isShowComments.splice(i, 1, !this.isShowComments[i]);
      this.commentsReply.forEach((item) => {
        item.isShowInput = false;
      });
    },
    inputFocus() {
      var replyInput = document.getElementById("replyInput");
      replyInput.style.padding = "8px 8px";
      replyInput.style.border = "2px solid blue";
      replyInput.focus();
    },
    showReplyBtn() {
      this.btnShow = true;
    },
    hideReplyBtn() {
      this.btnShow = false;
      replyInput.style.padding = "10px";
      replyInput.style.border = "none";
    },
    showReplyInput(i, name, id) {
      this.comments[this.index].inputShow = false;
      this.index = i;
      this.comments[i].inputShow = true;
      this.to = name;
      this.toId = id;
    },
    _inputShow(i) {
      return this.comments[i].inputShow;
    },
    //删除评论(文章的评论)
    async deleteComment(item) {
      let res = await this.$api.deleteComment(item.commentId, item.userId);
      if (res.code === 200) {
        this.$message({
          showClose: true,
          type: "success",
          message: "删除成功",
        });
        //获取文章评论;
        let commentRes = await this.$api.reqArticleComments(
          this.$store.state.article.artId
        );
        if (commentRes.code === 200) {
          //写入文章评论总数
          this.$store.commit("article/SET_COMMENTSNUM", commentRes.total);
          //更改数组中的时间格式
          for (let item of commentRes.rows) {
            item.time = renderTime(item.time);
            item.avatar = this.$api.BASEURL + item.avatar;
          }
          //写入文章评论数组
          this.$store.commit("article/SET_COMMENTS", commentRes.rows);
          this.comments = commentRes.rows;
        }
      }
      // console.log(res);
    },
    //删除评论(评论的评论)
    async deleteCommentReply(item, j) {
      let res = await this.$api.deleteComment(item.commentId, item.userId);
      if (res.code === 200) {
        this.$message({
          showClose: true,
          type: "success",
          message: "删除成功",
        });
        let res = await this.$api.getComments(item.commentId);
        if (res.code === 200) {
          for (let item of res.rows) {
            item.time = renderTime(item.time);
            item.avatar = this.$api.BASEURL + item.avatar;
          }
          this.commentsReply = res.rows;
        }
        this.isShowComments.splice(j, 1, true);
        this.commentsReply.forEach((item) => {
          item.isShowInput = false;
        });
      }

      // console.log(res);
    },
    //发送评论（评论评论）
    async sendComment(responseid, i, commentId) {
      if (!this.commentForm.content) {
        this.$message({
          showClose: true,
          type: "warning",
          message: "发表的评论不能为空",
        });
      } else {
        let input = this.commentForm.content;
        // let timeNow = new Date().getTime();
        // let time = this.dateStr(timeNow);
        // console.log("我是回复评论id" + responseid);
        // console.log("我是评论内容", input);
        // console.log("我是userId", this.$store.state.user.userId);
        // console.log("我是楼主id", commentId);
        let res = await this.$api.addComments({
          responseid: responseid,
          comment: input,
          userId: this.$store.state.user.userId,
          thumbups: commentId,
        });
        // console.log(res);
        if (res.code === 200) {
          this.$message({
            showClose: true,
            type: "success",
            message: "评论成功",
          });
          this.commentForm.content = "";
          let res = await this.$api.getComments(commentId);
          if (res.code === 200) {
            for (let item of res.rows) {
              item.time = renderTime(item.time);
              item.avatar = this.$api.BASEURL + item.avatar;
            }
            this.commentsReply = res.rows;
          }
          //改变数据是监听不到的
          this.isShowComments.splice(i, 1, true);
          this.commentsReply.forEach((item) => {
            item.isShowInput = false;
          });
        }
      }
    },
    // onDivInput: function (e) {
    //   this.replyComment = e.target.innerHTML;
    // },
    dateStr(date) {
      //获取js 时间戳
      var time = new Date().getTime();
      //去掉 js 时间戳后三位，与php 时间戳保持一致
      time = parseInt((time - date) / 1000);
      //存储转换值
      var s;
      if (time < 60 * 10) {
        //十分钟内
        return "刚刚";
      } else if (time < 60 * 60 && time >= 60 * 10) {
        //超过十分钟少于1小时
        s = Math.floor(time / 60);
        return s + "分钟前";
      } else if (time < 60 * 60 * 24 && time >= 60 * 60) {
        //超过1小时少于24小时
        s = Math.floor(time / 60 / 60);
        return s + "小时前";
      } else if (time < 60 * 60 * 24 * 30 && time >= 60 * 60 * 24) {
        //超过1天少于30天内
        s = Math.floor(time / 60 / 60 / 24);
        return s + "天前";
      } else {
        //超过30天ddd
        var date = new Date(parseInt(date));
        return (
          date.getFullYear() +
          "/" +
          (date.getMonth() + 1) +
          "/" +
          date.getDate()
        );
      }
    },
  },
  mounted() {
    //初始化isShowComments数组（是否展开子评论）
    this.isShowComments = new Array(this.comments.length);
    for (let j = 0; j < this.comments.length; j++) {
      this.isShowComments[j] = false;
    }
    //初始化isShowInput数组（是否显示楼主的评论框）
    this.isShowInput = new Array(this.comments.length);
    for (let j = 0; j < this.comments.length; j++) {
      this.isShowInput[j] = false;
    }
  },
};
</script>

<style scoped lang="less">
.img-face {
  width: 40px;
  height: 40px;
  border-radius: 20px;
}
.submit-comment {
  width: 50px;
  height: 30px;
}
.comments {
  .reply-father {
    border-bottom: 1px solid rgba(178, 186, 194, 0.3);
    margin-top: 10px;
  }
  .author-title {
    text-align: left;
    padding: 5px;
    &:last-child {
      border-bottom: 0px;
    }
  }
  .header-img {
    display: inline-block;
    vertical-align: top;
  }
  .author-info {
    display: inline-block;
    margin-left: 20px;
    width: 60%;
    height: 40px;
    line-height: 20px;
    span {
      display: block;
      cursor: pointer;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
    .author-name {
      font-size: 16px;
    }
    .author-time {
      font-size: 13px;
      color: #c1c1c1;
    }
  }
  .icon-btn {
    width: 30%;
    text-align: right;
    padding: 0 !important;
    float: right;
    @media screen and (max-width: 1200px) {
      width: 20%;
      padding: 7px;
    }
    .delete-btn {
      color: #c1c1c1;
      cursor: pointer;
      &:hover {
        color: #fc5632;
      }
    }
    span {
      cursor: pointer;
    }
    .iconfont {
      margin: 0 5px;
    }

    .reply-comment-btn {
      color: #c1c1c1;
      &:hover {
        color: @themeColor;
      }
      .icon-reply {
        font-size: 22px;
        margin-right: 0px;
        vertical-align: bottom;
      }
    }
    .comment-btn {
      color: #c1c1c1;
      &:hover {
        color: @themeColor;
      }
    }
  }
  .talk-box {
    margin: 10px 50px;
    .reply-to {
      color: #c1c1c1;
    }
    p {
      margin: 0;
    }
    .reply {
      font-size: 16px;
    }
  }
  .input-in-comment {
    margin-left: 50px;
    border-top: 10px;
  }
  .reply-box {
    margin: 10px 0 0 50px;
    // background-color:#efefef;
  }
  .my-reply {
    padding: 10px;
    // background-color:#fafbfc;
    .header-img {
      display: inline-block;
      vertical-align: top;
    }
    .reply-info {
      display: inline-block;
      margin-left: 5px;
      width: 90%;
      @media screen and (max-width: 1200px) {
        width: 80%;
      }
      .reply-input {
        min-height: 20px;
        line-height: 22px;
        padding: 10px 10px;
        color: #ccc;
        background-color: #fff;
        border-radius: 5px;
        &:empty:before {
          content: attr(placeholder);
        }
        &:focus:before {
          content: none;
        }
        &:focus {
          padding: 8px 8px;
          border: 2px solid blue;
          box-shadow: none;
          outline: none;
        }
      }
    }
    .reply-btn-box {
      height: 25px;
      margin: 10px 0;
      .reply-btn {
        position: relative;
        float: right;
        margin-right: 15px;
      }
    }
  }
  .my-comment-reply {
    margin-left: 50px;
    .reply-input {
      width: flex;
    }
  }
}
</style>
